#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <linux/can.h>
#include <linux/can/raw.h>

int sendCanMessage(const char* interface, struct can_frame frame) {
    int s;
    struct sockaddr_can addr;
    struct ifreq ifr;

    // 创建CAN原始套接字
    if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
        perror("Error while opening socket");
        return -1;
    }

    // 设置接口名
    strcpy(ifr.ifr_name, interface);
    if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
        perror("Error while getting interface index");
        close(s);
        return -1;
    }

    // 绑定套接字到指定的CAN接口
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;
    if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("Error while binding socket");
        close(s);
        return -1;
    }

    // 发送CAN消息
    if (write(s, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {
        perror("Error while sending CAN frame");
        close(s);
        return -1;
    }

    printf("Sent CAN message successfully\n");
    close(s);
    return 0;
}

int main() {
    struct can_frame frame;
    frame.can_id = 0x98; // CAN ID
    frame.can_dlc = 8;     // 数据长度
    // 填充数据
    for (int i = 0; i < 8; i++)
        frame.data[i] = i;

    if (sendCanMessage("vcan0", frame) == 0)
        printf("Message sent.\n");
    else
        printf("Failed to send message.\n");

    return 0;
}